import store from "@/store";
import socket from "@/socket";
import { Toast } from "vant";
import router from "@/router";

const even = [
    {   // 监听发来的消息
        name: 'receive_message_friend',
        fun : (message, callback) => {
            store.commit('upMessage', message);
            store.commit('upLastMessages', message);
            let audio = new Audio("audio/" + store.state.promptTone);
            audio.play();
        }
    },
    {   // 监听好友请求
        name: 'listen_applications',
        fun : (data, callback) => {
            store.commit('newFriend/pushApplications', data);
        }
    },
    {   // 监听添加好友结果
        name: 'listen_friend_addResulst',
        fun : async (data, callback) => {
            if (data.status_code == 200) {// 添加成功刷新好友列表
                let res_friend = await store.dispatch('login/getFriends', store.state.user.phone);
                if (res_friend.status_code != 200) {
                    Toast.fail(`好友获取失败: ${res_friend.error}`);  
                    return
                }   
                let arr = [];
                res_friend.friends.forEach(item => arr.push(item))
                store.commit('upFriend', arr);
                
                // 好友添加成功，从本地状态中删除这条请求
                const requestIndex = store.state.newFriend.applications.findIndex(
                    item => item._id === data.applications_id
                );
                
                if (requestIndex !== -1) {
                    store.state.newFriend.applications.splice(requestIndex, 1);
                }
                
                // 显示提示消息
                Toast.success(data.info || "好友添加成功");
            } else if (data.status_code == 403) { // 被拒绝
                // 显示被拒绝的提示信息
                Toast.fail(data.info || "对方拒绝了您的好友请求");
                // 更新状态
                delete data.status_code;
                store.commit('newFriend/upApplicationStatus', data);
            } else {
                // 其他情况，更新状态
                delete data.status_code;
                store.commit('newFriend/upApplicationStatus', data);
            }
        }
    },
    {   // 接收群聊信息
        name: 'receive_message_groupChat',
        fun : (data, callback) => {
            if (data.sender == store.state.user._id) {
                return;
            }
            store.commit('upMessage', data);
            store.commit('upLastMessages', data);
        }
    },
    {   // 加入成功群聊，刷新群聊，连接到新群聊
        name: 'joined_groupChat',
        fun : async (data, callback) => {
            if (data.status_code != 200) {
                return;
            }
            
            let res_groupChats = await store.dispatch('login/getGroupChats', store.state.user.phone);
            if (res_groupChats.status_code != 200)
            {
                Toast.fail(`status: ${ res_groupChats.status_code }, err: ${ res_groupChats.data }`);
                return;
            }
            
            store.commit('upGroupChats', res_groupChats.data);
            await store.dispatch('login/connectToGroupChats', store.state.user.phone);
        }
    },
    {   // 朋友发了新【动态】
        name: 'new_dynamic_friend',
        fun  : (data, callback) => {
            console.log(data);
            store.commit('userInfo/pushDynamic_G', data);
        }
    },
    {   // 被好友删除
        name: 'friendDeleted',
        fun: (data, callback) => {
            // 显示提示消息
            Toast.fail(data.message);
            
            // 更新好友列表
            if (data.friends) {
                // 清空当前store中的好友列表
                store.state.friendList.splice(0, store.state.friendList.length);
                // 用服务器返回的最新数据更新store
                store.commit('upFriend', data.friends);
            }
            
            // 获取被删除好友的用户ID
            const deletedById = data.deletedBy?.userId;
            
            // 如果当前正在与该好友聊天，则导航到好友列表页面
            if (router.currentRoute.path === '/chat' && router.currentRoute.query.user_id === deletedById) {
                router.push('/friend');
            }
            
            // 如果当前正在查看该好友的详情页面，也导航到好友列表页面
            if (router.currentRoute.path === '/home' && router.currentRoute.query.user_id === deletedById) {
                router.push('/friend');
            }
            
            // 如果当前正在该好友的设置页面，也导航到好友列表页面
            if (router.currentRoute.path === '/moreOperate' && router.currentRoute.query.user_id === deletedById) {
                router.push('/friend');
            }
        }
    }
]

const initListeners = () => even.forEach(even => {
    socket.on(even.name, (data, callback) => even.fun(data, callback))
});

export default initListeners;